<template>
  <div class="user-management-container">
    <el-row :gutter="20">
      <el-col :span="7">
        <el-form :inline="false" class="form-container">
          <el-form-item>
            <el-select class="full-width-select" v-model="skuIdList" placeholder="请选择SKU" multiple filterable>
              <el-option v-for="(item,key) in skuList" :value="item.id" :key="key"
                         :label="item.label"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-row>
              <el-col :span="24">
                <el-button class="full-width-button" icon="el-icon-search" type="primary" @click="fetchTree">
                  查询SKU
                </el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
        <el-card style="height:calc(80vh - 30px);overflow-y:auto">
          <el-tree
            :data="treeData"
            :props="defaultProps"
            v-loading="listLoadingTree"
            @node-click="handleNodeClick"
            @node-expand="handleNodeExpand"
            @node-collapse="handleNodeCollapse"
            node-key="sku_id"
          >
            <template #default="{ node, data }">
              <div class="custom-tree-node">
                <i :class="data.icon"></i> <!-- 图标 -->
                <el-tooltip :content="node.label" placement="top-start" effect="dark"
                            :disabled="getTooltipContent(node.label)">
                  <span class="node-label">{{ node.label }}</span> <!-- 节点文本 -->
                </el-tooltip>
              </div>
            </template>
          </el-tree>
        </el-card>
      </el-col>
      <el-col :span="17">
        <el-card>
          <el-table
            v-loading="listLoading"
            border
            :data="list"
            row-key="id"
            :row-class-name="rowClassName"
            ref="tableRef"
          >
            <el-table-column prop="no" label="类型" align="center">
              <template #default="{row}">
                BOM
              </template>
            </el-table-column>
            <el-table-column prop="no" label="层级结构" align="center"  width="80">
              <template #default="{row}">
                <el-button plain :type="(row.level % 6)|statusFilter"   @click="getChildrenBom(row)">{{row.level}}级</el-button>

              </template>
            </el-table-column>
            <el-table-column label="SKU编号/名称" width="300" align="center">
              <template #default="{row}">
                <el-tag  :type="(row.level % 6)|statusFilter" >{{ row.sku.code }}</el-tag>
                <br>
                <br>
                {{row.sku.label}}
              </template>
            </el-table-column>
            <el-table-column label="图片" align="center" width="100">
              <template #default="{row}">
                <template v-if="row.pic.length || row.sku.pic_path">
                <el-image v-for="(item,key) in row.pic" :src="fileRootPath+item" @click="imgPreview($event)" :key="key" />
                <el-image :src="fileRootPath+row.sku.pic_path" @click="imgPreview($event)" v-if="row.sku.pic_path"/>
                </template>
                <span v-else>无图片</span>
              </template>
            </el-table-column>
            <el-table-column prop="sku.label" label="SKU规格名称" align="left" header-align="center" >
              <template #default="{row}">
                <el-row v-for=" item in row.sku.attribute_spec" :key="item.id">
                  <span><b>{{ item.name }}:</b>{{ item.value }}</span>
                </el-row>
              </template>
            </el-table-column>
            <el-table-column prop="sku.label" label="生产属性统计" align="left" header-align="center" width="160">
              <template #default="{ row }">
                <b>总重量:</b>{{ new Intl.NumberFormat('en-US', {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
              }).format(parseFloat(row.weight.toFixed(2)))}}KG
                <el-row v-for="item in row.spec_weight" :key="item.id" class="text-block">
                  <span><b>{{ item.name }}</b>: {{ (item.weight/row.weight*100 ).toFixed(2)}}%</span>
                </el-row>
              </template>
            </el-table-column>
            <el-table-column label="物料占比" align="center" width="100">
              <template #default="{row}">
                <span>{{row.percentage.toFixed(2)}}</span>%
              </template>
            </el-table-column>
            <template #empty>
              <el-image
                class="vab-data-empty"
                :src="require('@/assets/empty_images/data_empty.png')"
              />
            </template>
          </el-table>
          <el-image-viewer v-if="imgPreviewVisible" :url-list="imgSrc" :on-close="imgPreviewClose"/>
        </el-card>
      </el-col>

    </el-row>
  </div>
</template>

<script>
import {getFile, recursionList as getRecursionList} from '@/api/bom/bom'
import {parseTime} from '@/utils/index'
import ElImageViewer from "element-ui/packages/image/src/image-viewer";
import {all as getSkuList} from "@/api/sku/classify";


export default {
  name: 'bomOrder',
  components: {ElImageViewer},
  filters: {
    parseTime: parseTime,
    statusFilter(status) {
      const statusMap = {
        0: 'danger',
        1: 'success',
        2: 'primary',
        3: 'info',
        4: 'warning',
      }
      return statusMap[status]
    },
    readFilter(status) {
      const statusMap = {
        1: '文本',
        2: '枚举',
        3: '日期',
        4: '数字',
        5: '百分比',
        6: '附件',
      }
      return statusMap[status]
    },
  },
  data() {
    return {
      skuList: [],
      skuIdList:[],
      level :0,
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      treeData: [
        {
          label: '一级 1',
          icon: 'el-icon-folder', // 图标类名
          children: [
            {
              label: '二级 1-1',
              icon: 'el-icon-document', // 图标类名
              children: [
                {
                  label: '三级 1-1-1',
                  icon: 'el-icon-document', // 图标类名
                },
              ],
            },
          ],
        },
        {
          label: '一级 2',
          icon: 'el-icon-folder', // 图标类名
          children: [
            {
              label: '二级 2-1',
              icon: 'el-icon-document', // 图标类名
            },
            {
              label: '二级 2-2',
              icon: 'el-icon-document', // 图标类名
            },
          ],
        },
      ],
      imgPreviewVisible: 0,
      list: [],
      listLoading: true,
      listLoadingTree: true,
      layout: 'total, sizes, prev, pager, next, jumper',
      total: 0,
      selectRows: '',
      queryForm: {
        pageNo: 1,
        pageSize: 10,
        level :0,
        bom_id:0
      },
      imgSrc: [],
    }
  },
  created() {
    this.fileRootPath = process.env.VUE_APP_FILE_ROOT_PATH
    this.fetchData()
    this.fetchTree()
    getSkuList({pageNo: 'all'}).then(response => {
      this.skuList = response.data.list
    });
  },
  methods: {
    rowClassName({ row, rowIndex }) {
      // 如果行是子行（即有parent属性），返回'child-row'类名
      if (row.children) {
        return '';
      }else {
        return 'child-row';
      }

    },
    initParentReferences(data) {
      data.forEach(item => {
        if (item.children && item.children.length > 0) {
          item.children.forEach(child => {
            child.parent = item; // 设置子行的parent属性为父行对象
          });
          this.initParentReferences(item.children); // 递归处理子行
        }
      });
    },
    getTooltipContent(label) {
      const maxLength = 20; // 设置最大长度，超过这个长度时显示 tooltip
      if (label.length > maxLength) {
        return false;
      } else
        return true; // 如果文本长度不超过 maxLength，返回空字符串，不显示 tooltip
    },
    imgPreviewClose() {
      this.imgPreviewVisible = 0
      this.imgSrc.pop()
    },
    imgPreview(event) {
      var el = event.currentTarget
      this.imgPreviewVisible = 1
      this.imgSrc.push(el.src)
    },
    async fetchData() {
      this.listLoading = true
      const {
        data: {list, total},
      } = await getFile(this.queryForm)
      this.list = list
      this.total = total
      this.listLoading = false
      this.initParentReferences(this.list);
    },
    async fetchTree() {
      this.listLoadingTree = true
      const {
        data: {treeData},
      } = await getRecursionList({'sku_id':this.skuIdList})
      this.treeData = treeData
      this.listLoadingTree = false
    },
    handleNodeCollapse(data,node,event){
      data.icon = 'el-icon-folder'
      this.$set(data,'expand',true)
    },
    handleNodeExpand(data,node,event){
      data.icon = 'el-icon-folder-opened'
      this.$set(data,'expand',false)
    },
    handleNodeClick(data, node, event) {
      // node: 节点对象
      // data: 节点对应的数据
      // event: 原生点击事件
      // console.log('Node clicked:', node);
      // console.log('Data:', data);
      // console.log('Event:', event);
      // 你可以在这里处理点击事件的逻辑
      if (data.expand === false) {
        getRecursionList({'parent_sku_id': data.sku_id}).then(response => {
          this.$set(data, 'children', response.data.treeData);
          this.$set(data,'expand',true)
          node.expand(this.getTrue)
          data.icon = 'el-icon-folder-opened'
        });
      }else{
        this.$set(data,'expand',false)
        data.icon = 'el-icon-folder'
      }
      this.queryForm.sku_id = data.sku_id
      this.queryForm.bom_id=0
      this.queryForm.parent_sku_id = node.parent.data.sku_id
      this.fetchData()
      this.level = node.level

    },
    getTrue(){
      return true
    },
    getChildrenBom(row){
      this.listLoading = true
      getFile({'parent_sku_id':row.sku_id,'level':row.level,'bom_id':row.bom_id.join(',')}).then(response=>{
        var new_list = []
        for(var i=0;i<response.data.list.length;i++){
          // if (response.data.list[i].bom_id.length){
          //   response.data.list[i].percentage = response.data.list[i].bom_weight/row.link_weight*row.percentage
          //   new_list.push(response.data.list[i])
          // }
          response.data.list[i].percentage = response.data.list[i].bom_weight/row.link_weight*row.percentage
          new_list.push(response.data.list[i])
        }
         this.$set(row,'children',new_list)
      })
      this.$refs.tableRef.toggleRowExpansion(row);
      this.listLoading = false
    }

  },
}
</script>
<style scoped>

.child-row {
  background-color: #265b09; /* 示例背景颜色 */
  color: #c41313; /* 示例字体颜色 */
  /* 其他样式 */
}

/* 树形节点的样式，如果需要调整可以在这里添加 */
.custom-tree-node {
  display: flex;
  align-items: center;
}

.custom-tree-node i {
  margin-right: 8px;
}
.text-block {
  text-align: left; /* 文本块左对齐 */
  display: inline-block; /* 确保文本块以内联块的形式显示 */
  width: 100%; /* 占满整个单元格宽度 */
}
.node-label {
  /* 设置宽度限制，确保文本超出时显示省略号 */
  display: inline-block;
  max-width: 400px; /* 根据实际需求调整宽度 */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  vertical-align: top;
}
.full-width-button {
  width: 100%; /* 按钮宽度与父容器相同 */
  display: inline-block; /* 使按钮可以水平居中 */
}
.full-width-select {
  width: 100%; /* 按钮宽度与父容器相同 */
  display: inline-block; /* 使按钮可以水平居中 */
}
</style>
